#include "list.h"
#include "panic.h"
#include "types.h"
#include "stdio.h"

/* @note: all the linked list here don't have a list head,
 * 	which means the first node of the list stores the data and
 * 	if there is not any node, the head pointer is NULL
 */

/* @brief: add a node to the front of the linked list
 * @param head: the head pointer of the linked list
 * @param node: pointer of the node to be added
 */
void list_add_front(struct linked_list **head, struct linked_list *node) {
	node->next = *head;
	*head = node;
}

/* @brief: add a node to the back of the linked list
 * @param head: the head pointer of the linked list
 * @param node: pointer of the node to be added
 */
void list_add_back(struct linked_list **head, struct linked_list *node) {
	struct linked_list *p = *head;
	// if list is empty
	if (*head == NULL) {
		*head = node;
		return;
	}
	// if list is not empty
	while (p->next != NULL) {
		p = p->next;
	}
	p->next = node;
	node->next = NULL;
}

/* @brief: remove a node from the front of the linked list
 * @param head: the head pointer of the linked list
 * @return: the removed node pointer
 */
struct linked_list *list_rm_front(struct linked_list **head) {
	struct linked_list *p;
	struct linked_list *rm;
	if (*head == NULL) {
		puts("list_rm_front: no enough node\n");
		return NULL;
	}
	p = (*head)->next;
	rm = *head;
	rm->next = NULL;
	*head = p;
	return rm;
}

/* @brief: remove a node of the linked list
 * @param head: the head pointer of the linked list
 * @param node: the node to be deleted
 * @return: the removed node pointer
 */
void list_rm(struct linked_list **head, struct linked_list *node) {
	struct linked_list *p = *head;
	if (*head == node) {
		list_rm_front(head);
		return;
	}
	while (p->next != node) {
		p = p->next;
	}
	p->next = node->next;
	node->next = NULL;
}
